"use client"

import { useState } from "react"
import { LEVELS } from "../config/levels"
import { ProgressBar } from "./progress-bar"
import { NPCCharacter } from "./npc-character"
import { DialogueBox } from "./dialogue-box"
import { GameControls } from "./game-controls"

interface GameLevelProps {
  levelId: string
  persuasionValue: number
  onPersuasionChange: (value: number) => void
  onComplete: () => void
  onRestart: () => void
  onBack: () => void
}

export function GameLevel({
  levelId,
  persuasionValue,
  onPersuasionChange,
  onComplete,
  onRestart,
  onBack,
}: GameLevelProps) {
  const [playerInput, setPlayerInput] = useState("")
  const [npcResponse, setNpcResponse] = useState("")
  const [isProcessing, setIsProcessing] = useState(false)

  const level = LEVELS[levelId]

  const generateNPCResponse = (input: string, currentPersuasion: number) => {
    const responses = {
      guard: {
        positive: ["你的诚实让我印象深刻，年轻人。", "真诚的话语总是能打动人心。", "我开始相信你的品格了。"],
        negative: ["空洞的话语无法说服我。", "你需要展现更多的诚意。", "守卫的职责不允许我轻易相信陌生人。"],
        danger: ["我对你的信任正在消失...", "再这样下去，你将被驱逐出城！"],
      },
      minister: {
        positive: ["聪明的策略，值得考虑。", "你展现出了政治家的智慧。", "这个提议很有见地。"],
        negative: ["这种想法过于天真。", "宫廷政治比你想象的复杂。", "你需要更深层的思考。"],
        danger: ["你的无知让我失望...", "也许你不适合宫廷生活。"],
      },
      king: {
        positive: ["你的真心让朕感动。", "难得有人能如此坦诚。", "你配得上朕的信任。"],
        negative: ["华丽的辞藻掩盖不了空虚的内心。", "朕见过太多虚伪的人。", "你需要展现真正的品格。"],
        danger: ["朕的耐心有限...", "你正在失去最后的机会！"],
      },
    }

    const levelResponses = responses[levelId as keyof typeof responses]
    if (!levelResponses) return "..."

    if (currentPersuasion <= level.dangerThreshold) {
      return levelResponses.danger[Math.floor(Math.random() * levelResponses.danger.length)]
    }

    // Simple sentiment analysis based on keywords
    const positiveKeywords = ["诚实", "真诚", "帮助", "服务", "忠诚", "智慧", "策略", "合作", "真心", "品格"]
    const hasPositiveWords = positiveKeywords.some((word) => input.includes(word))
    const isLongEnough = input.length >= 10

    if (hasPositiveWords && isLongEnough) {
      return levelResponses.positive[Math.floor(Math.random() * levelResponses.positive.length)]
    } else {
      return levelResponses.negative[Math.floor(Math.random() * levelResponses.negative.length)]
    }
  }

  const handleSubmit = async () => {
    if (!playerInput.trim() || isProcessing) return

    setIsProcessing(true)

    // Simple persuasion logic
    const positiveKeywords = ["诚实", "真诚", "帮助", "服务", "忠诚", "智慧", "策略", "合作", "真心", "品格"]
    const hasPositiveWords = positiveKeywords.some((word) => playerInput.includes(word))
    const isLongEnough = playerInput.length >= 10

    let change = 0
    if (hasPositiveWords && isLongEnough) {
      change = Math.floor(Math.random() * 15) + 10 // +10 to +25
    } else if (hasPositiveWords || isLongEnough) {
      change = Math.floor(Math.random() * 10) + 5 // +5 to +15
    } else {
      change = Math.floor(Math.random() * 10) - 15 // -15 to -5
    }

    const newValue = Math.max(0, Math.min(level.maxPersuasion, persuasionValue + change))
    onPersuasionChange(newValue)

    const response = generateNPCResponse(playerInput, newValue)
    setNpcResponse(response)

    // Check for completion
    if (newValue >= level.maxPersuasion) {
      setTimeout(() => {
        alert(`恭喜！你成功完成了${level.name}！`)
        onComplete()
      }, 1000)
    } else if (newValue <= 0) {
      setTimeout(() => {
        alert(`失败！你失去了所有信任，试炼失败。`)
        onRestart()
      }, 1000)
    }

    setPlayerInput("")
    setIsProcessing(false)
  }

  return (
    <div className="min-h-screen relative overflow-hidden">
      {/* Background */}
      <div
        className="absolute inset-0 bg-cover bg-center"
        style={{
          backgroundImage: "linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)",
        }}
      />

      {/* Overlay */}
      <div className="absolute inset-0 bg-black/50" />

      {/* Content */}
      <div className="relative z-10 flex flex-col items-center justify-center min-h-screen p-6">
        <div className="w-full max-w-4xl">
          {/* Title */}
          <h1 className="text-white text-3xl font-bold text-center mb-8">{level.name}</h1>

          {/* Progress Bar */}
          <ProgressBar
            value={persuasionValue}
            max={level.maxPersuasion}
            dangerThreshold={level.dangerThreshold}
            normalColor={level.normalColor}
            dangerColor={level.dangerColor}
            label="信任度"
          />

          {/* NPC Character */}
          <NPCCharacter image={level.image} borderColor={level.borderColor} name={level.name} />

          {/* Dialogue Box */}
          <DialogueBox
            response={npcResponse}
            input={playerInput}
            onInputChange={setPlayerInput}
            onSubmit={handleSubmit}
            disabled={isProcessing}
          />
        </div>

        {/* Game Controls */}
        <GameControls onRestart={onRestart} onBack={onBack} />
      </div>
    </div>
  )
}
